package com.cqggrw.interceptorAndFilter;

import java.io.File;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cqggrw.domain.User;
import com.cqggrw.util.Utils;

public class UrlFilter implements Filter {
	private HttpServletRequest req = null;
	private HttpServletResponse resp = null;
	private String contextPath = null;
	private String realPath = null;
	private String urlPath = null;
	private String filePath = null;

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		this.req = (HttpServletRequest) request;
		this.resp = (HttpServletResponse) response;
		
		this.contextPath = req.getContextPath();
		Utils.log(this.contextPath);
		this.realPath = req.getSession().getServletContext().getRealPath("");
		this.urlPath = req.getRequestURI();
		Utils.log(urlPath);
		this.filePath = this.realPath+this.urlPath.replace(this.contextPath, "").replace("/", Utils.separator);
		Utils.log(filePath);
		
		if((urlPath.indexOf("Admin") != -1) && (urlPath.indexOf("Login.jsp") == -1)) {
			User user = (User) req.getSession().getAttribute("user");
			if(user == null) {
				//resp.sendRedirect("Admin/Login.jsp");
				req.getRequestDispatcher("/Admin/Login.jsp").forward(req, resp);
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
		
		/*if(chekUrl()) {
		} else if(service()) {
			chain.doFilter(request, response);
		}*/
	}
	
	public boolean service() {
		boolean flag = true;
		Utils.log("service...");
		if(!chekFileExists()) {
			flag = false;
			try {
				req.getRequestDispatcher("/index.jsp").forward(req, resp);
			} catch (Exception e) {
				Utils.log(e);
			}
		}
		return flag;
		
	}
	
	/**
	 * 判断是否访问的是/Admin目录下面的页面
	 * @return
	 */
	public boolean chekUrl() {
		return this.urlPath.indexOf("/Admin") != -1;
	}
	
	/**
	 * 判断文件是否存在
	 * @return
	 */
	public boolean chekFileExists() {
		return new File(filePath).exists();
	}

	public void init(FilterConfig comfig) throws ServletException {

	}

}
